import { Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/database/mysql/entity/user.entity';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';
import { BusinessException } from 'src/types/exception/business.exception';
@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}
  async signIn(username: string, password: string): Promise<any> {
    const user = await this.userRepository.findOne({ where: { username } });
    if (!user) {
      throw new BusinessException({
        code: 'LOGIN_NOT_CORRECT',
        msg: '账号不存在',
      });
    }
    if (user.password !== password) {
      throw new BusinessException({
        code: 'LOGIN_NOT_CORRECT',
        msg: '密码错误',
      });
    }
    const payload = { userId: user?.id, username: user?.username };
    return { token: this.jwtService.sign(payload) };
  }
  login(createAuthDto: CreateAuthDto) {
    return createAuthDto;
  }
}
